﻿using System;
using System.Linq;
using BlogML.Xml;
using NGM.BlogML.Models;
using Orchard.ContentManagement;
using Orchard.Tags.Services;

namespace NGM.BlogML.Services.Stratagies {
    public class CategoryReferencesImportStratagy : IMultipleImportStratagy {
        private readonly ITagService _tagService;

        public CategoryReferencesImportStratagy(ITagService tagService) {
            _tagService = tagService;
        }

        public bool IsType(object objectToImport) {
            return objectToImport is BlogMLPost.CategoryReferenceCollection;
        }

        public ContentItem Import(ImportSettings importSettings, BlogMLBlog blog, object objectToImport, IContent parentContent) {
            var categoriesToImport = (BlogMLPost.CategoryReferenceCollection)objectToImport;

            if (categoriesToImport.Count == 0)
                return null;

            var tags = categoriesToImport.Cast<BlogMLCategoryReference>()
                .Select(t => blog.Categories.First(c => c.ID == t.Ref));

            foreach (var tag in tags) {
                if (_tagService.GetTagByName(tag.Title) == null) {
                    _tagService.CreateTag(tag.Title);
                }
            }

            _tagService.UpdateTagsForContentItem(parentContent.ContentItem, tags.Select(t => t.Title));

            return null;
        }

        public void ImportAdditionalContentItems<T>(ImportSettings importSettings, BlogMLBlog blog, T objectToImport, IContent parentContent) {
            throw new NotSupportedException();
        }
    }
}